﻿using Common.Exception;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStructCenter
{
    public class DoublyLinkedList<T>
    {
        //链表头指针
        public DoublyNode<T> Head { get; set; }
        //链表尾指针
        public DoublyNode<T> Tail { get; set; }
        
        public DoublyNode<T> Push(T value)
        {
            var node = new DoublyNode<T>(value);
            if (Head == null)
            {
                Head = Tail = node;
            }
            else
            {
                node.PrePoint = null;
                node.NextPoint = Head;
                Head.PrePoint = node;
                Head = node;
            }
            
            return Head;
        }

        public DoublyNode<T> AddToTail(T value)
        {
            var node = new DoublyNode<T>(value);
            if (Tail == null)
            {
                Head = Tail = node;
            }
            else
            {
                Tail.NextPoint = node;
                node.PrePoint = Tail;
                Tail = node;
                Tail.NextPoint = null;
            }

            return Tail;
        }

        /// <summary>
        /// 链表头部弹出
        /// </summary>
        public void Pop()
        {
            if (Head == Tail)
            {
                Head = Tail = null;
                return;
            }
            Head = Head.NextPoint;
            Head.PrePoint = null;           
        }

        /// <summary>
        /// 链表尾部删除
        /// </summary>
        public void DelFromTail()
        {
            if (Head == Tail)
            {
                Tail = Head = null;
                return;
            }
            Tail = Tail.PrePoint;
            Tail.NextPoint = null;
        }

        public void DelNode(DoublyNode<T> node)
        {
            
            if (node == Head)
            {
                Pop();
                return;
            }
            if (node == Tail)
            {
                DelFromTail();
                return;
            }
            node.PrePoint.NextPoint = node.NextPoint;
            node.NextPoint.PrePoint = node.PrePoint;
            node = null;
        }



    }
}
